﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Infrastructure;
using Infrastructure.Dao;
using SqlSugar;
using WsdShop.IService;
using WsdShop.Model;
using WsdShop.Model.SearchModels;

namespace WsdShop.Service
{
    public class AdService : IAdService
    {
        public List<AdConfiguration> AdManage(AdSearchModel search, out int total)
        {
            using (var Db = DbConfig.GetInstance())
            {
                Sqlable sable = Db.Sqlable().From<AdConfiguration>("");
                if (!search.Keywords.IsNullOrEmpty())
                {
                    sable.Where(" Tittle like @tittle ");
                }
                if (search.TypeId > 0)
                {
                    sable.Where(" TypeId=@typeId ");
                }

                var pars = new { tittle = "%" + search.Keywords + "%", typeId = search.TypeId };
                total = sable.Count(pars);
                var list = sable.SelectToPageList<AdConfiguration>("*", search.OrderByFields, search.Skip / search.Take + 1, search.Take, pars);
                return list;
            }
        }


        public AdConfiguration AdEdit(int Id)
        {
            using (var Db = DbConfig.GetInstance())
            {
                if (Id == 0)
                {
                    return new AdConfiguration();
                }
                else
                {
                    return Db.Queryable<AdConfiguration>().SingleOrDefault(m => m.Id == Id);
                }
            }
        }


        public Result AdEditSubmit(AdConfiguration submitData, int currentUserId)
        {
            if (submitData == null)
            {
                return Result.Failure("传入参数有误");
            }

            using (var Db = DbConfig.GetInstance())
            {
                if (submitData.Id == 0)
                {
                    submitData.AddUserId = currentUserId;
                }
                else
                {
                    submitData.EditTime = DateTime.Now;
                    submitData.EditUserId = currentUserId;
                }
                Db.InsertOrUpdate(submitData);
                return Result.Success();
            }
        }


        public Result DelAd(int Id, int currentUserId)
        {
            if (Id == 0)
            {
                return Result.Failure("该数据不存在");
            }

            using (var Db = DbConfig.GetInstance())
            {
                if (Db.Update<AdConfiguration>(new { IsDeleted = true }, m => m.Id == Id))
                {
                    return Result.Success();
                }
                return Result.Failure("操作失败");
            }
        }
    }
}
